package com.quanquan.management.core.service;

import java.io.Serializable;
import java.util.List;

import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.repository.JpaRepository;


public class GenericService<T extends Serializable, ID extends Serializable> {

    private JpaRepository<T, ID> genericRepository;

    public List<T> findAll() {
        return getGenericRepository().findAll();
    }

    public List<T> findAll(Sort sort) {
        return getGenericRepository().findAll(sort);
    }


    public void flush() {
        getGenericRepository().flush();
    }

    public <S extends T> S save(S entity) {
        return getGenericRepository().save(entity);
    }

    public <S extends T> S saveAndFlush(S entity) {
        return getGenericRepository().saveAndFlush(entity);
    }

    public void deleteInBatch(Iterable<T> entities) {
        getGenericRepository().deleteInBatch(entities);
    }

    public void deleteAllInBatch() {
        getGenericRepository().deleteAllInBatch();
    }

    public T getOne(ID id) {
        return getGenericRepository().getOne(id);
    }

    public <S extends T> List<S> findAll(Example<S> example) {
        return getGenericRepository().findAll(example);
    }

    public <S extends T> List<S> findAll(S s) {
        Example<S> example = Example.of(s);
        return findAll(example);
    }

    public <S extends T> S find(S s) {
        Example<S> example = Example.of(s);
        List<S> lst = findAll(example);
        return lst.size() > 0 ? lst.get(0) : null;
    }

    public <S extends T> List<S> findAll(Example<S> example, Sort sort) {
        return getGenericRepository().findAll(example, sort);
    }

    public Page<T> findAll(Pageable pageable) {
        return getGenericRepository().findAll(pageable);
    }

    public long count() {
        return getGenericRepository().count();
    }

    public JpaRepository<T, ID> getGenericRepository() {
        return genericRepository;
    }

    public void setGenericRepository(JpaRepository<T, ID> genericRepository) {
        this.genericRepository = genericRepository;
    }

}
